<?php
session_start();
require_once '../utils/Response.php';
require_once '../config/dbConfig.php';
global $conn;
connectDB();

/**
 * 根据id查询用户信息
 * @param $id
 * @return void
 */
function getUserById($id){
    global $conn;
    $sql = "SELECT * FROM user WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i",$id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_all(MYSQLI_ASSOC);

    Response::success('获取成功', $data)->send();

    $stmt->close();
    $conn->close();
}


/**
 * 根据id更新用户信息
 * @param $id
 * @param $data
 * @return void
 */
function updateUserById($id, $data)
{
    global $conn;

    $username = $data['username'] ?? null;
    $name = $data['name'] ?? null;
    $phone = $data['phone'] ?? null;
    $email = $data['email'] ?? null;
    $address = $data['address'] ?? null;
    $password = $data['password'] ?? '';

    // 检查是否需要更新密码
    if (!empty($password)) {
        // 如果密码不为空，则更新包括密码在内的所有字段
        $sql = "UPDATE user SET username = ?, name = ?, phone = ?, email = ?, address = ?, password = ? WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssssi", $username, $name, $phone, $email, $address, $password, $id);
    } else {
        // 如果密码为空，则只更新除密码外的其他字段
        $sql = "UPDATE user SET username = ?, name = ?, phone = ?, email = ?, address = ? WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssi", $username, $name, $phone, $email, $address, $id);
    }

    if ($stmt->execute()) {
        Response::success('用户信息更新成功')->send();
        $_SESSION['user_id'] = $id;
        $_SESSION['username'] = $username;
    } else {
        Response::error('用户信息更新失败', $stmt->error)->send();
    }
    $stmt->close();
}